#pragma once

#include "Socket.hpp"
#include "InetAddr.hpp"
#include <memory>
#include <unistd.h>
#include <signal.h>
#include <functional>

using callback_t = std::function<std::string(std::string&)>;

// 服务器只做IO工作
class TcpServer
{
public:
    TcpServer(int port, callback_t cb)
        : _port(port),
          _listensocket(std::make_unique<TcpSocket>()),
          _cb(cb)
    {
        _listensocket->BuildListenSocketMethod(_port);
    }

    void HandlerRequest(std::shared_ptr<Socket> sockfd, InetAddr addr)
    {
        std::string inbuffer;
        while (true)
        {
            // 接受数据
            ssize_t n = sockfd->Recv(&inbuffer);
            if (n > 0)
            {
                LOG(LogLevel::INFO) << addr.ToString() << "# " << inbuffer;
                // 这里将数据丢给上层处理，服务器只负责IO
                std::string send_str = _cb(inbuffer);
                if (send_str.empty())
                    continue;
                sockfd->Send(send_str);
            }
            else if (n == 0)
            {
                LOG(LogLevel::INFO) << addr.ToString() << " client quit, me too!";
                break;
            }
            else
            {
                LOG(LogLevel::DEBUG) << addr.ToString() << " read error, quit!";
                break;
            }
        }
        sockfd->Close();
    }

    void Run()
    {
        signal(SIGCHLD, SIG_IGN);
        while (true)
        {
            InetAddr addr;
            auto sockfd = _listensocket->AcceptSocketOrDie(&addr);
            if (sockfd == nullptr)
                continue;
            LOG(LogLevel::DEBUG) << "获取一个新连接: " << addr.ToString()
                                 << ", sockfd : " << sockfd->Sockfd();
            if (fork() == 0)
            {
                _listensocket->Close();
                HandlerRequest(sockfd, addr);
                exit(OK);
            }
            sockfd->Close();
        }
    }

    ~TcpServer()
    {
    }

private:
    int _port;
    std::unique_ptr<Socket> _listensocket;
    // 回调函数
    callback_t _cb;
};